package com.cashoutgaming.client.widgets.recent_matches;

import java.util.ArrayList;
import java.util.List;
import com.cashoutgaming.shared.game.GameType;
import com.cashoutgaming.shared.match.MatchDTO;
import com.cashoutgaming.shared.match.MatchDTOProperties;
import com.cashoutgaming.shared.match.MatchFilterDTO;
import com.cashoutgaming.shared.match.MatchPagingLoadResult;
import com.google.gwt.cell.client.ImageResourceCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safecss.shared.SafeStylesUtils;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sencha.gxt.cell.core.client.form.ComboBoxCell.TriggerAction;
import com.sencha.gxt.core.client.Style.SelectionMode;
import com.sencha.gxt.data.client.loader.RpcProxy;
import com.sencha.gxt.data.shared.LabelProvider;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.SortDir;
import com.sencha.gxt.data.shared.loader.LoadResultListStoreBinding;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoader;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.form.SimpleComboBox;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent.SelectionChangedHandler;
import com.sencha.gxt.widget.core.client.toolbar.FillToolItem;
import com.sencha.gxt.widget.core.client.toolbar.PagingToolBar;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;

public class RecentMatchesPanel extends ContentPanel {

	private static final MatchDTOProperties props = GWT.create(MatchDTOProperties.class);
	private final RecentMatchesView view;
	private Grid<MatchDTO> grid;
	private ToolBar toolbar;
	private SimpleComboBox<GameType> gameCombo;
	private ListStore<MatchDTO> store;

	// Filter Boxes
	private TextField searchField;

	// Paging Variables
	private PagingLoader<PagingLoadConfig, PagingLoadResult<MatchDTO>> loader;
	private AsyncCallback<PagingLoadResult<MatchDTO>> proxycallback;
	private static final int PER_PAGE = 20;
	private String sort_by;
	private SortDir sortDir;
	private int sort_dir;
	private int offset = 0;
	private PagingToolBar pagingToolBar;

	public RecentMatchesPanel(RecentMatchesView view) {
		this.view = view;
		buildUI();
	}

	public void buildUI() {
		setHeaderVisible(false);

		buildToolBar();
		buildGrid();
		final VerticalLayoutContainer vlc = new VerticalLayoutContainer();
		vlc.setBorders(false);
		vlc.add(toolbar, new VerticalLayoutData(1, -1));
		vlc.add(grid, new VerticalLayoutData(1, 1));
		vlc.add(pagingToolBar, new VerticalLayoutData(1, -1));
		add(vlc);
	}

	public void buildToolBar() {
		gameCombo = new SimpleComboBox<GameType>(new LabelProvider<GameType>() {

			@Override
			public String getLabel(GameType item) {
				return item.getFull();
			}
		});
		gameCombo.setTriggerAction(TriggerAction.ALL);
		gameCombo.setEmptyText("Game Type");
		gameCombo.setTypeAhead(true);

		for (final GameType theEnum : GameType.values()) {
			gameCombo.getStore().add(theEnum);
		}

		toolbar = new ToolBar();
		toolbar.setHeight(27);
		toolbar.add(new FillToolItem());
		toolbar.add(gameCombo);
		toolbar.forceLayout();
	}

	public void toggleContextSensitiveButtons() {
		toolbar.clear();

		toolbar.add(new FillToolItem());
		toolbar.add(gameCombo);
		toolbar.forceLayout();
	}

	public void buildGrid() {
		store = new ListStore<MatchDTO>(props.key());
		final RpcProxy<PagingLoadConfig, PagingLoadResult<MatchDTO>> proxy = new RpcProxy<PagingLoadConfig, PagingLoadResult<MatchDTO>>() {

			@Override
			public void load(final PagingLoadConfig loadConfig, final AsyncCallback<PagingLoadResult<MatchDTO>> callback) {
				offset = loadConfig.getOffset();
				if (loadConfig.getSortInfo().size() > 0) {
					sortDir = loadConfig.getSortInfo().get(0).getSortDir();
					sort_by = loadConfig.getSortInfo().get(0).getSortField();
				}
				else {
					sortDir = SortDir.ASC;
				}
				if (sortDir == SortDir.DESC) {
					sort_dir = 1;
				}
				else {
					sort_dir = 0;
				}

				// if (sort_by == null) {
				// sort_by = "last_name";
				// }
				//
				// if (sort_by.equalsIgnoreCase("getId")) {
				// sort_by = "id";
				// }
				// else if (sort_by.equalsIgnoreCase("getName")) {
				// sort_by = "name";
				// }
				// else if (sort_by.equalsIgnoreCase("getDescription")) {
				// sort_by = "description";
				// }

				proxycallback = callback;

				performSearch();
			}
		};

		loader = new PagingLoader<PagingLoadConfig, PagingLoadResult<MatchDTO>>(proxy);
		loader.setRemoteSort(true);
		loader.addLoadHandler(new LoadResultListStoreBinding<PagingLoadConfig, MatchDTO, PagingLoadResult<MatchDTO>>(store));

		pagingToolBar = new PagingToolBar(PER_PAGE);
		pagingToolBar.bind(loader);

		ColumnConfig<MatchDTO, ImageResource> gameIcon = new ColumnConfig<MatchDTO, ImageResource>(props.getGameIcon(), 100, "Game");
		gameIcon.setCell(new ImageResourceCell() {

			@Override
			public void render(com.google.gwt.cell.client.Cell.Context context, ImageResource value, SafeHtmlBuilder sb) {
				super.render(context, value, sb);
			}
		});
		gameIcon.setColumnStyle(SafeStylesUtils.fromTrustedString("vertical-align: middle; text-align: center; height: 25px;"));
		ColumnConfig<MatchDTO, String> teamOneName = new ColumnConfig<MatchDTO, String>(props.getTeamOneName(), 150, "Team One");
		ColumnConfig<MatchDTO, Integer> teamOneWins = new ColumnConfig<MatchDTO, Integer>(props.getTeamOneWins(), 30, "");
		ColumnConfig<MatchDTO, String> teamTwoName = new ColumnConfig<MatchDTO, String>(props.getTeamTwoName(), 150, "Team Two");
		ColumnConfig<MatchDTO, Integer> teamTwoWins = new ColumnConfig<MatchDTO, Integer>(props.getTeamTwoWins(), 30, "");
		ColumnConfig<MatchDTO, String> wager = new ColumnConfig<MatchDTO, String>(props.getWager(), 75, "Wager");

		List<ColumnConfig<MatchDTO, ?>> l = new ArrayList<ColumnConfig<MatchDTO, ?>>();
		l.add(gameIcon);
		l.add(teamOneName);
		l.add(teamOneWins);
		l.add(teamTwoName);
		l.add(teamTwoWins);
		l.add(wager);

		ColumnModel<MatchDTO> cm = new ColumnModel<MatchDTO>(l);
		grid = new Grid<MatchDTO>(store, cm);
		grid.getView().setStripeRows(true);
		grid.getView().setColumnLines(true);
		grid.getView().setAutoExpandColumn(gameIcon);
		grid.getView().setAutoExpandMin(150);
		grid.setColumnReordering(true);
		grid.setStateful(true);
		grid.setLoadMask(true);
		grid.setStateId("recentMatchesGrid");
		grid.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
		grid.setLoader(loader);
		grid.getSelectionModel().addSelectionChangedHandler(new SelectionChangedHandler<MatchDTO>() {

			@Override
			public void onSelectionChanged(SelectionChangedEvent<MatchDTO> event) {
				toggleContextSensitiveButtons();
			}
		});
	}

	public void loadData(MatchPagingLoadResult result) {
		result.setOffset(result.getOffset());
		proxycallback.onSuccess(result);
		if (mask) {
			unmask();
			toggleContextSensitiveButtons();
		}
	}

	public void performSearch() {
		mask();

		GameType game = gameCombo.getCurrentValue();
		MatchFilterDTO filter = new MatchFilterDTO(game, offset, PER_PAGE, sort_by, sort_dir);

		view.getUiHandlers().getMatches(filter);
	}

	public void load() {
		loader.load();
	}
}
